package com.tg.paw.common.resolver;


import com.tg.paw.common.annotation.LoginAdmin;
import com.tg.paw.common.component.UserUtil;
import com.tg.paw.common.entity.User;
import com.tg.paw.common.entity.UserAdmin;
import com.tg.paw.common.feign.AdminServiceFeignClient;
import com.tg.paw.common.util.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Token转化 UmsAdmin
 *
 * @author mall
 * @date 2018/12/21
 */
@Slf4j
public class LoginAdminTokenArgumentResolver implements HandlerMethodArgumentResolver {
    private AdminServiceFeignClient adminServiceFeignClient;

    public LoginAdminTokenArgumentResolver(AdminServiceFeignClient adminServiceFeignClient) {
        this.adminServiceFeignClient = adminServiceFeignClient;
    }

    /**
     * 入参筛选
     *
     * @param methodParameter 参数集合
     * @return 格式化后的参数
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(LoginAdmin.class) && methodParameter.getParameterType().equals(UserAdmin.class);
    }

    /**
     * @param methodParameter       入参集合
     * @param modelAndViewContainer model 和 view
     * @param nativeWebRequest      web相关
     * @param webDataBinderFactory  入参解析
     * @return 包装对象
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) {
         LoginAdmin loginAdmin = methodParameter.getParameterAnnotation(LoginAdmin.class);
        boolean isFull = loginAdmin.isFull();
        User user = UserUtil.getLoginUser();
        UserAdmin userAdmin = new UserAdmin();
        userAdmin.setUserName(user.getUserName());
        user.setUserId(user.getUserId());
        if (isFull) {
            CommonResult<UserAdmin> commonResult = adminServiceFeignClient.currentUser();
            userAdmin = commonResult.getData();
        }
        return userAdmin;
    }
}
